package com.sdp.right.websocket.server;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.sdp.right.websocket.dto.MessageInfo;

import lombok.extern.slf4j.Slf4j;

@ServerEndpoint("/websocket")
@Component
@Slf4j
public class MessageWebsocketServer {
	
	/**
     * 存放所有在线的客户端，key:sessionId
     */
	private static Map<String, Session> clients = new ConcurrentHashMap<>();
	
	/*
	 * 存放用户对应的多个客户端sessionId的map
	 */
	private static Map<String, Map<String, String>> empClientIdMap = new ConcurrentHashMap<>();
	
	
	@OnOpen
	public void onOpen(Session session) {
		log.info("有新的客户端连接了, sessionId: {}", session.getId());
		clients.put(session.getId(), session);
	}

	@OnClose
	public void onClose(Session session) {
		log.info("有客户端断开连接了, sessionId: {}", session.getId());
		clients.remove(session.getId());
		
		for (String empNo : empClientIdMap.keySet()) {
			Iterator<Entry<String, String>> iterator = empClientIdMap.get(empNo).entrySet().iterator();
			while (iterator.hasNext()) {
				Entry<String, String> entry = iterator.next();
				if (session.getId().equals(entry.getKey())) {
					iterator.remove();
				}
			}
		}
	}

	@OnError
	public void onError(Session session, Throwable throwable) {
		for (StackTraceElement stackTraceElement : throwable.getStackTrace()) {
			log.error(stackTraceElement.toString());
		}
	}

	@OnMessage
	public void onMessage(String message, Session session) {
		log.info("有客户端发送消息了, sessionId: {}", session.getId());
		if (!StringUtils.isEmpty(message)) {
			MessageInfo messageInfo = JSON.parseObject(message, MessageInfo.class);
			if (!StringUtils.isEmpty(messageInfo.getEmpNo())) {
				if (!empClientIdMap.containsKey(messageInfo.getEmpNo())) {
					synchronized (empClientIdMap) {
						if (!empClientIdMap.containsKey(messageInfo.getEmpNo())) {
							Map<String, String> tempMap = new ConcurrentHashMap<>();
							empClientIdMap.put(messageInfo.getEmpNo(), tempMap);						
						}
					}
				}
				//添加empNo与通道sessionId的对应关系
				empClientIdMap.get(messageInfo.getEmpNo()).put(session.getId(), session.getId());
			} else {
				log.info("客户端发送消息格式不正确，缺少empNo, sessionId: {}, messaage: {}", session.getId(), message);
			}
			
		} else {
			log.info("客户端发送消息为空, sessionId: {}", session.getId());
		}
		
	}

	
	public void sendMessage(MessageInfo message) {
		if (!StringUtils.isEmpty(message.getEmpNo())) {
			if (empClientIdMap.containsKey(message.getEmpNo())) {
				String text = JSON.toJSONString(message);
				for (String sessionId : empClientIdMap.get(message.getEmpNo()).keySet()) {
					if (clients.get(sessionId).isOpen()) {
						try {
							clients.get(sessionId).getBasicRemote().sendText(text);
						} catch (Exception e) {
							log.error("服务端发送消息失败, sessionId: {}, messaage: {}", sessionId, text);
						}
						
					}
				}
			}
		}
	}

	public static Map<String, Map<String, String>> getEmpClientIdMap() {
		return empClientIdMap;
	}

}
